require(["common", "coAjax", "queryString", "routie"], function(jSouper, coAjax, QueryString, routie) {
	//放置监听HASH变动
	function _init_hash() {
		routie({
			"*": function(hash) {
				var queryString = new QueryString(location.hash);
				var tag_id = queryString.get("tag_id") || App.get("$Cache.tags.list.0._id");
				coAjax.get(appConfig.tag.list_detail_by_id, {
					tag_id: tag_id,
					bus_id: appConfig.bus_id
				}, function(result) {
					App.set("$Cache.pointer_tag", result.result);
				});
			}
		});
	}

	// 加载标签列表
	// coAjax.get(appConfig.bus.tags_detail,{
	// 	bus_id:appConfig.bus_id
	// },function (result) {
	// 	App.set("$Cache.tags_detail",result.result);
	// 	_init_hash();
	// });	
	coAjax.get(appConfig.tag.list, {
		bus_id: appConfig.bus_id
	}, function(result) {
		App.set("$Cache.tags.list", result.result);
		_init_hash();
	});

	// 直接购买
	function _get_cart_success(result) {
		var cart_detail = result.result;

		App.set("user.cart_detail", cart_detail);
		App.set("$Cache.cart.total_price", Model.Observer(function() {
			var cart_detail = App.get("user.cart_detail");
			var total_price = 0;
			cart_detail.forEach(function(cart) {
				cart.goods_info.forEach(function(goods_info) {
					total_price += goods_info.goods.price * goods_info.num;
				});
			});
			return total_price;
		}));
		alert("success", "添加成功")
	};

	function _get_cart_error(errorCode, xhr, errorMsg) {
		console.log("%c" + errorCode + ": " + errorMsg, "color:orange;font-size:14px; text-shadow: 0 1px 0 #ccc;");
		alert("error", errorMsg);
	};
	App.set("$Event.goods_list.add_to_cart", function(e, vm) {
		App.set("$private", 'focus');
		var cart_item = {
			goods_id: vm.get("_id"),
			num: 1
		};
		if (App.get("loginer")) {
			coAjax.post(appConfig.user.cart, cart_item, _get_cart_success, _get_cart_error);
		} else {
			var cache_cart = LS.get("$Cache.cart");
			try {
				cache_cart = JSON.parse(cache_cart);
			} catch (e) {
				console.error(e)
			}
			if (!(cache_cart instanceof Array)) {
				cache_cart = [];
			}
			cache_cart.push(cart_item);
			LS.set("$Cache.cart", JSON.stringify(cache_cart));
		}
	});
});